package com.gonsin.gview.common.auth;

import com.gonsin.base.ResponseResult;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 自定义一个切面类，利用aspect实现切入所有方法
 *
 * @author spc
 */
@Aspect
@Component
public class NoRepeatSubmitAop {

    private final Log logger = LogFactory.getLog(getClass());

    /**
     * 重复提交判断时间为3s
     */
    private final Cache<String, Long> cache = CacheBuilder.newBuilder().expireAfterWrite(2400, TimeUnit.SECONDS).build();


//    @Pointcut("@annotation(noRepeatSubmit)")
//    public void pointCut(NoRepeatSubmit noRepeatSubmit) {
//    }

    @Around("execution(@com.gonsin.gview.common.auth.NoRepeatSubmit * *(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        try {
            MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
            Method method = joinPointObject.getMethod();
            NoRepeatSubmit nrs = method.getAnnotation(NoRepeatSubmit.class);
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
            assert attributes != null;
            HttpServletRequest request = attributes.getRequest();
            String key = sessionId + "-" + request.getServletPath();
            // 如果缓存中有这个url视为重复提交
            Long validateTime = cache.getIfPresent(key);
            if (validateTime == null) {
                cache.put(key, System.currentTimeMillis() + nrs.lockTime() * 1000L);
            } else {
                long now = System.currentTimeMillis();
                if(now < validateTime){
                    int waitSecond = (int) ((validateTime - now) / 1000);
                    return ResponseResult.simpleResult(BaseResultCodes.TOO_FAST.getValue(),
                            String.format("操作过快，请再等待%d秒", waitSecond));
                }
                cache.invalidate(key);
            }
            return pjp.proceed();
        } catch (Throwable e) {
//            e.printStackTrace();
//            logger.error("验证重复提交时出现未知异常!");
//            return new RuntimeException("验证重复提交时出现未知异常!");
            throw e;
        }
    }

}